package com.example.webcomen.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.webcomen.Mapper.*;
import com.example.webcomen.Model.*;
import com.example.webcomen.Utill.ToInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BaseInfoService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private AddMessageMapper addMessageMapper;
    @Autowired
    private FriendGroupDetailMapper friendGroupDetailMapper;
    @Autowired
    private FriendGroupMapper friendGroupMapper;
    @Autowired
    private GroupMemberMapper groupMemberMapper;
    @Autowired
    private MessageMapper messageMapper;

    public FriendGroup createNewFriendGroup(String gName,Integer uid){
        QueryWrapper<FriendGroup> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        queryWrapper.eq("group_name",gName);
        if(friendGroupMapper.selectOne(queryWrapper)==null){
            friendGroupMapper.insert(new FriendGroup(uid,gName));
        }
        return friendGroupMapper.selectOne(queryWrapper);
    }

    public AddMessage createNewAddMessage(AddMessage addMessage){
        QueryWrapper<AddMessage> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("from_uid",addMessage.getFromUid());
        queryWrapper.eq("to_uid",addMessage.getToUid());
        queryWrapper.eq("type",addMessage.getType());
        if(!addMessageMapper.exists(queryWrapper)){
            addMessageMapper.insert(addMessage);
            return addMessageMapper.selectOne(queryWrapper);
        }
        return null;
    }

    public List<UserInfo> selectUsersByUserName(String serName){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("username",serName);
        return ToInfo.toUserInfo(userMapper.selectList(queryWrapper));
    }
    public List<GroupInfo> selectGroupsByGroupName(String serName){
        QueryWrapper<Group> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("group_name",serName);
        return ToInfo.toGroupInfo(groupMapper.selectList(queryWrapper));
    }
//    找到特定id的用户
    public User selecetUserById(Integer i){
        return userMapper.selectById(i);
    }
//    找到某用户所有联系人分组
    public List<FriendGroup> findOneAllFriendGroup(Integer uid){
        QueryWrapper<FriendGroup> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",uid);
        return friendGroupMapper.selectList(wrapper);
    }
//    找到一个联系人分组中的所有用户
    public List<User> findAllUserInTheGroup(Integer fgid){
        QueryWrapper<FriendGroupDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("fgid",fgid);
        List<User> userList=new ArrayList<>();
        List<FriendGroupDetail> friendGroupDetails=friendGroupDetailMapper.selectList(wrapper);
        friendGroupDetails.forEach(friendGroupDetail -> {
            userList.add(selecetUserById(friendGroupDetail.getUid()));
        });
        return userList;
    }
//    找到一个用户的所有联系人分组（二阶结构）
    public List<FriendGroupInfo> findOneFriendGroups(Integer id){
        List<FriendGroupInfo> friendGroupInfos=new ArrayList<>();
        List<FriendGroup> friendGroups=findOneAllFriendGroup(id);
        friendGroups.forEach(friendGroup -> {
            FriendGroupInfo groupInfo=ToInfo.toFriendGroupInfo(friendGroup);
            groupInfo.setList(ToInfo.toUserInfo(findAllUserInTheGroup(friendGroup.getId())));
            friendGroupInfos.add(groupInfo);
        });
        return  friendGroupInfos;
    }
//    找到一个用户的所有群聊
    public List<GroupInfo> findAllGroupById(Integer uid){
        List<GroupInfo> groupInfos=new ArrayList<>();
        List<GroupMember> groupMembers= groupMemberMapper.selectList(
                new QueryWrapper<GroupMember>().eq("uid",uid));
        groupMembers.forEach(groupMember -> {
            groupInfos.add(ToInfo.toGroupInfo(groupMapper.selectById(groupMember.getGid())));
        });
        return groupInfos;
    }
    //    找到一个群聊的所有组员
    public List<UserInfo> findAllUserInTheFriendGroup(Integer gid){
        QueryWrapper<GroupMember> wrapper=new QueryWrapper<>();
        wrapper.eq("gid",gid);
        List<UserInfo> userList=new ArrayList<>();
        List<GroupMember> groupMembers=groupMemberMapper.selectList(wrapper);
        groupMembers.forEach(groupMember -> {
            User user=selecetUserById(groupMember.getUid());
            if (user!=null)
                userList.add(ToInfo.toUserInfo(user));
        });
        return userList;
    }

    public boolean addUser(User user){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        if (user.getEmail()!=null&&user.getUsername()!=null) {
            wrapper.eq("email", user.getEmail());
            wrapper.eq("username", user.getUsername());
        }
        if (!userMapper.selectList(wrapper).isEmpty())
            return  false;
        userMapper.insert(user);
        return  true;
    }

    public User selectByUserName(String username){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectOne(wrapper);
    }

    public User findHoster(Integer gid){
        return userMapper.selectById(groupMapper.selectById(gid).getCreateId());
    }
    public Integer findHosterId(Integer gid){
        return userMapper.selectById(groupMapper.selectById(gid).getCreateId()).getId();
    }
    public String findHosterName(Integer gid){
        return userMapper.selectById(groupMapper.selectById(gid).getCreateId()).getUsername();
    }

    public List<AddMessageInfo> findOnesAddInvitationInfo(Integer id){
        QueryWrapper<AddMessage> wrapper=new QueryWrapper<>();
        wrapper.eq("to_uid",id);
        wrapper.eq("agree",0);
        return ToInfo.toAddMessageInfoList(addMessageMapper.selectList(wrapper));}
    public String findGroupNameByGID(Integer gid){
        Group group=groupMapper.selectById(gid);
        return group==null? " ":group.getGroupname();
    }

    public List<AddMessage> findOnesAddInvitation(Integer id){
        QueryWrapper<AddMessage> wrapper=new QueryWrapper<>();
        wrapper.eq("to_uid",id);
        wrapper.eq("agree",0);
        return addMessageMapper.selectList(wrapper);}

    public boolean agreeAddMessageU(String nofz,Integer messId,Integer uid){
//        单方面提出申请，然后单方面接受申请

        QueryWrapper<FriendGroup> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",uid);
        wrapper.eq("group_name",nofz);
        AddMessage oldAddMessage=addMessageMapper.selectById(messId);
        AddMessage addMessage=new AddMessage();
        addMessage.setId(messId);
        FriendGroupDetail from=new FriendGroupDetail();
        FriendGroupDetail to=new FriendGroupDetail();
        FriendGroup friendGroup=null;

        QueryWrapper<AddMessage> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("from_uid",oldAddMessage.getToUid());
        queryWrapper.eq("to_uid",oldAddMessage.getFromUid());
        queryWrapper.eq("agree",0);
        if (addMessageMapper.exists(queryWrapper)){
            AddMessage addMessage1=addMessageMapper.selectOne(queryWrapper);
            addMessage1.setAgree(1);
            addMessageMapper.updateById(addMessage1);
        }

        if (nofz!=null&&nofz!=""&&friendGroupMapper.exists(wrapper)){
            friendGroup=friendGroupMapper.selectOne(wrapper);
        }else {
            friendGroup=createNewFriendGroup("默认分组",uid);
        }
        addMessage.setAgree(1);
        addMessageMapper.updateById(addMessage);

        from.setFgid(oldAddMessage.getGroupId());
        from.setUid(oldAddMessage.getToUid());
        friendGroupDetailMapper.insert(from);

        to.setFgid(friendGroup.getId());
        to.setUid(oldAddMessage.getFromUid());
        friendGroupDetailMapper.insert(to);
        return true;
    }

    public boolean deneyInvit(Integer messageId){
        QueryWrapper<AddMessage> wrapper=new QueryWrapper<>();
        wrapper.eq("id",messageId);
        if (addMessageMapper.exists(wrapper)){
            addMessageMapper.deleteById(messageId);
        }
        return true;
    }
}
